package com.weilele.mvvm.base

import android.os.Bundle
import android.view.*
import android.widget.EditText
import android.widget.FrameLayout
import com.weilele.mvvm.utils.android_r.ImeHelper2
import com.weilele.mvvm.utils.android_r.showIme

/**
 * 专门处理需要软键盘输入的对话框
 */
abstract class MvvmImeDialog : MvvmDialog() {

    override fun getClickView(): List<View?>? = null

    override fun initUi(savedInstanceState: Bundle?) {
        initIme()
    }

    override fun initData() {
    }

    override fun onSingleClick(view: View) {
    }


    override fun onRootViewLayoutParams(lp: FrameLayout.LayoutParams) {
        super.onRootViewLayoutParams(lp)
        lp.gravity = Gravity.BOTTOM
    }

    abstract fun getFocusViewView(): EditText?


    private fun initIme() {
        val window = dialog?.window ?: return
        //防止布局变化
        //由于会在activity监听键盘，所以和dialog的window无关，设置为SOFT_INPUT_ADJUST_NOTHING，能更好控制布局
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
        ImeHelper2(this).apply {
            setOnImeListener { offset, imeHeight, statusHeight, navigationBarHeight ->
                if (!onImeStatusChange(offset, imeHeight, statusHeight, navigationBarHeight)) {
                    view?.setPadding(0, 0, 0, offset - navigationBarHeight)
                }
            }
        }
    }

    override fun onStart() {
        super.onStart()
        getFocusViewView()?.let {
            it.post { it.showIme() }
        }
    }

    /**
     * 键盘状态发生变化的回调
     * 返回值 false，布局会根据键盘状态改变
     * ture：自己处理逻辑
     */
    open fun onImeStatusChange(
        offSet: Int,
        imeHeight: Int,
        statusBarHeight: Int,
        navigationBarHeight: Int
    ): Boolean {
        return false
    }
}